<template>
  <div class="vc-page vc-page-parts page-Perm" style="position:relative;overflow:hidden;">
    <!-- 左侧 - 用户组树 -->
    <div class="part-left">
      <div class="tree-title">
        <span>模块组树</span>
        <el-tooltip content="刷新" placement="bottom">
          <i @click="filterText='';getAllRole()" class="vc-icon vc-icon-refresh"></i>
        </el-tooltip>
      </div>
      <el-input
        v-if="rgTreeData.length"
        v-model="filterText"
        placeholder="请输入关键字"
        class="vc-search-input"
        size="small"
        clearable>
      </el-input>
      <el-tree
        :current-node-key="curkey"
        :data="rgTreeData"
        :defaultExpandedKeys="expandedKeys"
        :empty-text="treeEmptyText"
        :expand-on-click-node="false"
        :props="defaultProps"
        :render-after-expand="true"
        :filter-node-method="filterNode"
        @node-click="rghandleNodeClick"
        @node-collapse="hideRightMenu"
        @node-expand="hideRightMenu"
        class="org-tree"
        highlight-current
        node-key="id"
        ref="rgTree"
      >
        <span
          @mouseenter="point = data"
          @mouseleave="point = null"
          class="slot-scope"
          slot-scope="{ node, data }"
        >
          <span>
            <i :class="data.icon"></i>
            <span style="margin-left:5px;">{{ node.label }}</span>
            <i
              @click.stop="showHandleMenu(data, $event)"
              class="vc-icon vc-icon-more"
              v-if="point == data || (!point && data.id == currDicData.id && menuVisible)"
            ></i>
          </span>
        </span>
      </el-tree>
    </div>

    <!-- 右侧 - 详情与表格 -->
    <div class="part-right">
      <!--右侧节点信息-->
      <div>
        <div class="perm-info">
          <el-row>
            <el-col :span="24" class="title-class">
              <div class="icon-class bg-primary"></div>
              <span>权限信息</span>
            </el-col>
          </el-row>

          <el-row :key="idx" v-for="(item,idx) in rightText.itmes">
            <el-col :span="3" class="label">{{item.text}}</el-col>
            <el-col :span="21">
              <span
                v-if="item.type !=='dict'"
              >{{ rightText.params[item.key]?rightText.params[item.key]:' ' }}</span>
              <span
                v-else-if="item.type ==='dict'"
              >{{item.group[rightText.params[item.key]]?item.group[rightText.params[item.key]]:" "}}</span>
            </el-col>
          </el-row>
        </div>
      </div>

      <div>
        <!-- 操作按钮 -->
        <div class="vc-btns">
          <el-button
            :disabled="selectedIds.length === 0"
            @click="btnRemove"
            class="multi-words"
            size="small"
            type="primary"
          >移除操作</el-button>
        </div>

        <div class="vc-table">
          <!-- 列表展示 -->
          <tables
            :columns="tableConfig.columns"
            :stripe="true"
            @on-selection-change="handleSelectionChange"
            ref="tables"
            v-model="tableConfig.tableData"
          />
          <!-- 分页 -->
          <el-pagination
            :current-page.sync="currentPage"
            :page-size="GLOBAL.QUERY.PAGE_SIZE"
            :total="total"
            @current-change="handleCurrentChange"
            layout="total, prev, pager, next"
            v-if="paginationShow"
          ></el-pagination>
        </div>
      </div>
      <!-- 右键菜单展示 -->
      <ul class="menu-handle-right" id="menuCM" v-show="menuVisible">
        <li :key="idx" @click="item.click" v-for="(item,idx) in RightBox">{{item.title}}</li>
      </ul>
    </div>

    <!-- 新增模块 -->

    <add-module
      :addChildModelFlage="addChildModelFlage"
      :selectNode="selectNode"
      @close="addModuleClose"
    ></add-module>

    <!-- 新增权限 -->
    <add-permission
      :addPermission="addPermission"
      :selectNode="selectNode"
      @close="addPermissionClose"
    ></add-permission>
    <!-- 修改模块  -->
    <edit-module
      :patchModel="patchModel"
      :rgTreeDataHasTop="rgTreeDataHasTop"
      :selectNode="selectNode"
      @close="eidtModuleClose"
    ></edit-module>
    <!-- 修改权限 -->
    <edit-Perm
      :patchPerModel="patchPerModel"
      :rgTreeDataHasTop="rgTreeDataHasTop"
      :selectNode="selectNode"
      @close="editPermClose"
    ></edit-Perm>
  </div>
</template>

<script>
import AddModule from './addModule'
import supForm from '_c/form'
import Tables from '_c/tables'
import AddPermission from './addPermission'
import EditModule from './editModule'
import store from '@/store'
import EditPerm from './editPerm'
const SFGDMAP = store.state.dic.mapFormat['sfgd']

export default {
  name: 'permission',
  components: {
    AddModule,
    AddPermission,
    EditModule,
    EditPerm,
    Tables,
    supForm
  },
  computed: {
    trueFalseAllList() {
      return this.$store.state.dic.trueFalseAllList
    }
  },
  data() {
    return {
      currentNode: {},
      selectNode: {},
      disabled: false,
      currDicData: {},
      point: null,
      // 右侧 点击右键
      RightBox: [],
      // 右侧信息
      rightText: {
        title: '权限信息',
        itmes: [
          {
            text: '权限编码',
            key: 'code'
          },
          {
            text: '权限名称',
            key: 'name'
          },
          {
            text: '描述',
            key: 'descr',
            type: 'textarea'
          }
        ],
        params: {}
      },
      // 菜单
      menuVisible: false,
      addChildModelFlage: false,
      addPermission: false,
      patchModel: false,
      patchPerModel: false,
      // 右键单击对话框
      rightClickConfig: {
        deleteId: '',
        perDeleteId: ''
      },

      // 组织机构树
      curkey: '',
      treeEmptyText: ' ',
      rgTreeData: [],
      rgTreeDataHasTop: [],
      roleTreeData: [],
      expandedKeys: [],
      defaultProps: {
        id: 'id',
        label: 'text',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      filterText: '',

      // id存储用户点击的左侧树用户组节点的id
      id: '',
      name: '',
      pid: '',
      queryData: {
        name: ''
      },
      rolesearchData: {},
      tableEmptyText: this.GLOBAL.QUERY.LOADING_TEXT,
      paginationShow: true,
      currentPage: 1,
      total: 0,
      roleTableData: null,
      selectedIds: [],
      entity: {},
      // 表格数据
      tableConfig: {
        columns: [
          {
            type: 'selection',
            key: 'selection',
            title: '多选',
            width: 70
          },
          {
            title: '序号',
            type: 'index',
            width: 70
          },
          {
            title: '操作名称',
            key: 'name'
          },
          {
            title: '资源名称',
            key: 'resourceName'
          },
          {
            title: '资源类型',
            key: 'resourceType',
            formatType: this.formatResourceType
          },
          {
            title: '操作描述',
            key: 'descr'
          }
        ],
        tableData: []
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.rgTree.filter(this.GLOBAL.filter.filterSpace(val));
    }
  },
  mounted() {
    $('.org-tree').scroll(() => {
      this.hideRightMenu()
    })
    document.addEventListener('mousedown', this.mousedown)
    this.ini()
  },
  beforeDestroy() {
    document.removeEventListener('mousedown', this.mousedown)
  },
  methods: {
    /**
     * 关闭权限修改
     */
    editPermClose(value) {
      this.patchPerModel = false
      if (value) {
        this.reset()
        this.expandedKeys.push(this.selectNode.id)
        this.getAllRole(this.currentNode, false)
      }
    },
    /**
     * 关闭修改模块
     */
    eidtModuleClose(value) {
      this.patchModel = false
      if (value) {
        this.expandedKeys.push(this.selectNode.pid)
        this.reset()
        this.getAllRole(this.selectNode, true)
      }
    },
    /**
     * 关闭新增权限
     */
    addPermissionClose(value) {
      this.addPermission = false
      if (value) {
        this.expandedKeys.push(this.selectNode.id)
        this.reset()
        this.getAllRole(this.selectNode, false)
      }
    },
    /**
     * 关闭新增模块
     */
    addModuleClose(value) {
      this.addChildModelFlage = false
      if (value) {
        this.reset()
        this.getAllRole(this.selectNode, true)
        this.expandedKeys.push(this.selectNode.id)
      }
    },
    /**
     * 鼠标点击触发事件
     */
    mousedown(ev) {
      if (!this.menuVisible) return
      let pid = ev.target.parentElement.id
      if (pid !== 'menuCM') return this.hideRightMenu()
      if (ev.button !== 0) return
      ev.target.click()
      this.hideRightMenu()
    },
    /**
     * 隐藏右键菜单
     */
    hideRightMenu() {
      this.menuVisible = false
    },
    /*
      左侧右键模块修改 得到模块树
    */
    getAllModel() {
      this.$api.getMGroupTreeCurr().then(res => {
        if (!res.success) {
          return
        }
        var temp1 = res.data || []
        for (var i = temp1.length - 1; i >= 0; i--) {}
        temp1.forEach(i => {
          i = Object.assign(i, i.data)
        })
        temp1 = this.GLOBAL.array.transToTreeData(temp1)
        this.rightClickConfig.patchPerModelFormConfig.items[0].group = temp1
      })
    },
    /**
     * 设置是否内置数据的value。数据库只存是 否。但是前台有第三个选项全部。使用""空字符串作查询条件参数代表全部。服务器遇到空字符串作参数才会返回全部信息。
     */
    setInnerValue(val) {
      if (val.code === 2) {
        return ''
      } else {
        return val.code
      }
    },

    /**
     * 树节点右键点击时的回调
     */
    rightClick(data) {
      this.selectNode = data
      switch (data.type) {
        case 'mgroup':
          this.RightBox = this.mGroup()
          this.rightClickConfig.deleteId = data.id
          break
        case 'permission':
          this.RightBox = this.permission()
          this.rightClickConfig.perDeleteId = data.id
          break
        default:
          break
      }
    },
    /**
     * 显示树节点操作菜单
     */
    showHandleMenu(data, ev) {
      this.rightClick(data)
      this.currDicData = Object.assign({}, data)
      let $menu = $('#menuCM')
      if (ev.clientY + $menu.outerWidth() < innerHeight) {
        $menu.css('top', ev.clientY + 'px')
        $menu.css('bottom', 'auto')
      } else {
        $menu.css('top', 'auto')
        $menu.css('bottom', innerHeight - ev.clientY + 'px')
      }
      $menu.css('left', ev.clientX + 'px')
      this.menuVisible = true
    },
    /*
      配置模块右键内容
    */
    mGroup() {
      return [
        {
          title: '新增下级模块',
          click: row => {
            this.addChildModelFlage = true
            this.selectNode.isChild = true
          }
        },
        {
          title: '新增同级模块',
          click: row => {
            this.selectNode.isChild = false
            this.addChildModelFlage = true
          }
        },
        {
          title: '新增权限',
          click: () => {
            this.addPermission = true
          }
        },
        {
          title: '修改模块',
          click: () => {
            this.getAllModel()
            this.patchModel = true
          }
        },
        {
          title: '删除模块',
          click: () => {
            this.$confirmBox(this.deleteModel)
          }
        }
      ]
    },
    permission() {
      return [
        {
          title: '修改权限',
          click: () => {
            this.patchPerModel = true
            this.disabled = false
          }
        },
        {
          title: '删除权限',
          click: () => {
            this.$confirmBox(this.deletePer)
            this.disabled = false
          }
        }
      ]
    },
    /*
      删除模块
    */
    deleteModel() {
      this.$api
        .deleteMgroup({
          data: {
            id: this.selectNode.id
          }
        })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            if (this.selectNode.id !== this.currentNode.id) {
              this.getAllRole(this.currentNode)
            } else {
              this.getAllRole()
            }
          } else {
            this.getAllRole()
          }
        })
    },
    /*
      删除quanxian
    */
    deletePer() {
      this.$api
        .deletePer({
          data: {
            id: this.rightClickConfig.perDeleteId
          }
        })
        .then(res => {
          if (res.success) {
            this.$message.success('删除成功')
            this.expandedKeys.push(this.selectNode.pid)
            if (this.selectNode.id !== this.currentNode.id) {
              this.getAllRole(this.currentNode)
            } else {
              this.getAllRole()
            }
          }
        })
    },
    ini() {
      this.getAllRole()
    },
    btnRemove() {
      this.$confirmBox(this.removeRP, '你确定移除么')
    },
    removeRP() {
      this.$api
        .removeByResourceIdsAndPermissionId({
          data: {
            resourceIds: this.selectedIds,
            permissionId: this.id
          }
        })
        .then(res => {
          if (res.success) {
            this.$notifyBox('成功移除操作', 'success')

            this.getRightText([this.id])
          }
        })
    },

    /**
     * 用户组树节点被点击时的回调
     */
    rghandleNodeClick(data, node, self) {
      if (!data.type || data.type !== 'mgroup') {
        this.currentNode = data
        this.$nextTick(() => {
          this.id = data.id
          this.curkey = data.id
          this.$refs.rgTree.setCurrentKey(data.id)
          this.reset()
          this.getRightText([data.id])
        })
      } else {
        this.$nextTick(() => {
          this.$refs.rgTree.setCurrentKey(this.id)
        })
      }
    },

    /**
     * 格式化列表数据
     */
    formatResourceType(row) {
      return row.resourceType
        ? this.$store.state.dic.mapFormat['ZYLX'][row.resourceType]
        : ''
    },

    /**
     * 点击页数
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getRightText([this.id])
    },

    /**
     * 重置查询条件
     */
    reset() {
      this.queryData = this.GLOBAL.object.clearValOfObj(this.queryData)
    },

    /**
     * 复选框勾选记录勾选的值
     */
    handleSelectionChange(val) {
      this.selectedIds = this.GLOBAL.array.selectOneKey(val, 'resourceId')
    },

    /*
      获取右侧数据 先获取文本框数据
    */
    getRightText(ids) {
      this.$api
        .getPermissionByid({
          data: {
            ids: ids
          }
        })
        .then(res => {
          if (!res.success) {
            return
          }
          this.rightText.params = res.data[0]
          this.$api
            .getResourceByid({
              data: {
                permissionIds: ids,
                pageNum: this.currentPage,
                pageSize: 15
              }
            })
            .then(call => {
              if (call.success) {
                if (call.data.records.length !== 0) {
                  this.tableConfig.tableData = call.data.records
                  this.total = call.data.total
                  this.currentPage = call.data.current
                } else if (this.currentPage > 1) {
                  this.currentPage--
                  this.getRightText([this.id])
                } else {
                  this.tableConfig.tableData = []
                  this.currentPage = 1
                }
              }
            })
        })
    },

    /**
     * 获取左侧角色组树数据,用于各种操作完成后刷新页面。参数用于记住原先的树节点id.
     */
    getAllRole(checkedKey, isGroup = false) {
      this.$api.getMPTree().then(res => {
        this.treeEmptyText = this.GLOBAL.QUERY.EMPTY_TEXT;
        var temp1 = res.data
        for (var i = temp1.length - 1; i >= 0; i--) {
          // 添加图标
          if (temp1[i].type === 'permission') {
            temp1[i].icon = 'vc-icon vc-icon-tree-perm'
          } else {
            temp1[i].icon = 'vc-icon vc-icon-tree-module'
          }
        }
        this.rgTreeDataHasTop = this.GLOBAL.array.transToTreeData(temp1)
        this.rgTreeData = this.rgTreeDataHasTop
        if (!checkedKey) {
          this.expandedKeys = []
          let expandedKeys = []
          this.getFirst(this.rgTreeData, expandedKeys)
          this.expandedKeys.push(expandedKeys[0].id)
          this.curkey = expandedKeys[0].id // selectNode
          this.rghandleNodeClick(expandedKeys[0])
          return
        }
        let expandedKeys = this.$refs.rgTree.store
          ._getAllNodes()
          .filter(item => item.expanded === true)
          .map(item => item.key)
        this.expandedKeys = expandedKeys
        if (checkedKey && isGroup === true) {
          this.reset()
          this.rghandleNodeClick(checkedKey)
        }
        if (!isGroup && checkedKey) {
          this.rghandleNodeClick(checkedKey)
        }
      })
    },
    /*
      递归找第一个 type = 'permission'
    */
    getFirst(data, expandedKeys) {
      for (const i in data) {
        if (data[i]) {
          let node = data[i]
          if (node.type === 'permission') {
            expandedKeys.push(node)
            return
          } else if (node.children && node.children.length !== 0) {
            this.getFirst(node.children, expandedKeys)
          }
        }
      }
    },
    /*
      左侧树图标
    */
    renderContent(h, { node, data, store }) {
      return (
        <span>
          <i class={data.icon}></i>
          <span> {node.label}</span>
        </span>
      )
    },
    /**
     * 对树节点进行筛选
     */
    filterNode(value, data) {
      if (!value) return true;
      return data.text.indexOf(value) !== -1;
    }
  }
}
</script>

<style lang="less">
.valueClass {
  text-align: left;
}
.keyClass {
  display: flex;
  align-items: center;
  height: 40px;
  justify-content: flex-end;
  color: #999999;
  font-size: 15px;
}
.valueClass {
  display: flex;
  align-items: center;
  height: 40px;
  justify-content: flex-start;
  font-size: 15px;
}
.titleClass {
  display: flex;
  align-items: center;
  background-color: #ebeef5;
  height: 26px;
}
.iconClass {
  width: 5px;
  height: 15px;
  background-color: #2ab099;
  margin-right: 5px;
}
.page-Perm {
  .menu-info,
  .perm-info {
    margin-bottom: 30px;
    .title-class {
      height: 30px;
      display: flex;
      align-items: center;
      background-color: #ebeef5;
      font-size: 16px;
      .icon-class {
        width: 3px;
        height: 12px;
        margin-right: 8px;
      }
    }
    .el-col:not(.title-class) {
      line-height: 20px;
      margin: 10px 0;
      display: flex;
      align-items: center;
      &.label {
        justify-content: flex-end;
        color: #818181;
        padding-right: 20px;
      }
      &:not(.label) {
        text-align: left;
        word-wrap: break-word;
        word-break: break-all;
        overflow: hidden;
        i {
          font-size: 14px;
        }
      }
    }
    .el-row {
      &:nth-child(2) {
        margin-top: 10px;
      }
      &:last-child {
        margin-bottom: 10px;
      }
    }
  }
}
</style>
